package com.orangelife.mobile.individual.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.sp.UserSp;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.curry.android.view.gridpasswordview.GridPasswordView;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;
import com.orangelife.mobile.constants.Constant;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;


import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/3/3.
 */
public class PayPwdActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.gpv_normal)
    GridPasswordView gpvNormal;/*密码设置框*/
    @Bind(R.id.ll_pwd)
    LinearLayout llPwd;/*密码设置器*/
    @Bind(R.id.btn_submit)
    Button btnSubmit;/*提交按钮*/
    @Bind(R.id.ll_find)
    LinearLayout llFind;/*密码重置选择*/
    @Bind(R.id.ll_sms)
    LinearLayout llSms;/*短信验证*/
    @Bind(R.id.tv_title)
    TextView tvTitle;/*标题*/
    @Bind(R.id.tvPhoneNum)
    TextView tvPhoneNum;/*手机号码*/
    @Bind(R.id.et_code)
    TextView etCode;
    @Bind(R.id.btn_get_code)
    TextView tvGetCode;

    /* 倒计时的最大时间 */
    private int timeSendSms = 59;
    /* 计时器 */
    private Timer timer;

    private final int OLDPWD = 0;
    private final int NEWPWD = 1;

    private int key = NEWPWD;

    String pwd = null;/*第一次密码*/
    Boolean isFrirst = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paypwd);
        ButterKnife.bind(this);
        initView();
    }


    private void initView() {
        tvPhoneNum.setText(UserSp.getRegPhone());
        tvTitle.setText("设置支付密码");
        intiTime();
        initPwd();
    }

    private void intiTime() {
        timeSendSms = 59;
        tvGetCode.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.obtainMessage(Constant.WHAT_COUNT_DOWN, timeSendSms--)
                        .sendToTarget();
            }
        }, 0, 1000);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case Constant.WHAT_COUNT_DOWN:
                    if (timeSendSms >= 0) {
                        tvGetCode.setText(getResources()
                                .getString(R.string.wait)
                                + timeSendSms
                                + getResources().getString(R.string.seconds));

                    } else {
                        tvGetCode.setEnabled(true);
                        tvGetCode.setText(getResources().getString(
                                R.string.send_again));
                        timer.cancel();
                    }
                    break;
            }
        }
    };

    /**
     * 初始化新密码
     */
    private void initPwd() {
        gpvNormal.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {
                if (psw.length() == 6) {
                    if (pwd.length() == 6) {
                        if (psw.equals(pwd)) {
                            isFrirst = true;
                        }
                    } else if (pwd.length() == 0) {
                        pwd = psw;
                        btnSubmit.setVisibility(View.VISIBLE);
                        key = NEWPWD;
                    } else {
                        isFrirst = false;
                    }
                }
            }

            @Override
            public void onInputFinish(String psw) {

            }
        });
    }

    @OnClick({R.id.btn_submit, R.id.btn_get_code, R.id.btn_next})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if (isFrirst == true) {
                    Submit(NEWPWD, pwd);

                } else {

                }
                break;
            case R.id.btn_get_code:
                sendSMS(tvPhoneNum.getText().toString());
                break;
            case R.id.btn_next:
                break;
            default:
                senVerifySmsCode(tvPhoneNum.getText().toString(), etCode.getText().toString());
                break;
        }
    }


    /**
     * 验证码验证
     *
     * @param phone
     * @param codes
     */
    private void senVerifySmsCode(String phone, String codes) {
        if (StringUtil.isContainBlank(codes)) {
            ToastHelper.getInstance().displayToastWithQuickClose(
                    getResources().getString(
                            R.string.verification_code_null));
            return;
        }
        SmsHttpBiz.checkSmsVerifyCode(phone, codes, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                        .jsonToMap(String.valueOf(response.toString()));
                if (errCode == 0) {
                    llPwd.setVisibility(View.VISIBLE);
                    llSms.setVisibility(View.GONE);
                } else {
                    ToastHelper.getInstance()
                            .displayToastWithQuickClose(String.valueOf(map.get(Constant.RESULT_MESSAGE_KEY)));
                }
            }
        });
    }

    /**
     * 发送短信
     *
     * @param phone
     */
    private void sendSMS(String phone) {
        SmsHttpBiz.getSmsCode(phone, new VolleyHttpUtil.ResponseCallBack() {

            @Override
            public void handleResponse(JSONObject response, int errCode) {
                HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                        .jsonToMap(String.valueOf(response.toString()));
                if (errCode == Constant.RESULT_SUCCESS) {
                    ToastHelper.getInstance()
                            .displayToastWithQuickClose(
                                    getResources().getString(
                                            R.string.send_sms_success));
                } else {
                    ToastHelper.getInstance()
                            .displayToastWithQuickClose(String.valueOf(map.get(Constant.RESULT_MESSAGE_KEY)));
                    timeSendSms = 0;
                }
            }
        });
    }

    /**
     * 支付密码提交
     *
     * @param i
     * @param pwd
     */
    private void Submit(int i, String pwd) {
        switch (i) {
            case OLDPWD:
                verifyOldPwd(pwd);
                break;
            case NEWPWD:
                submitNewPwd(pwd);
                break;
            default:
                break;
        }
    }

    /**
     * 设置新支付密码
     *
     * @param pwd
     */
    private void submitNewPwd(String pwd) {
        finish();
    }

    private void verifyOldPwd(String pwd) {

    }
}
